const WebSocket = require('ws');
const fs = require('fs');
const path = require('path');

const htmlDir = path.join(__dirname, '../../mock-html');
const htmlFiles = fs.readdirSync(htmlDir).filter(file => file.endsWith('.html'));
const htmlContents = [];
htmlFiles.forEach(file => {
    const filePath = path.join(htmlDir, file);
    const content = fs.readFileSync(filePath, 'utf8');
    htmlContents.push(content);
});
let currentIndex = 0;

const setupWebSocket = (server) => {
    const wss = new WebSocket.Server({ server });

    console.log('WebSocket Mock 服务已启动，监听端口 5174');

    wss.on('connection', (ws) => {
        console.log('客户端已连接');

        ws.on('message', (message) => {
            console.log(`收到客户端消息: ${message}`);
            const response = htmlContents[currentIndex];
            ws.send(response);
            currentIndex++;
            if (currentIndex >= htmlContents.length) {
                currentIndex = 0;
            }
        });

        ws.on('close', () => {
            console.log('客户端已断开连接');
        });
    });
};

module.exports = {
    setupWebSocket
};